<template>
  <div mt-24px>
    <el-form :model="form" :label-position="mode === 'view' ? 'left' : 'right'" :hide-required-asterisk="mode === 'view'" :rules="rules" ref="ruleFormRef" class="form" :class="{'form-views': mode === 'view'}" label-width="130px">
      <el-form-item label="项目性质">
        <span>{{ projectNatureName }}</span>
      </el-form-item>
      <el-form-item :label="projectNature !== projectNatureEnum.projectNatureHorizontal ? '项目编号' : '合同编号'"
        :prop="isProposal ? '' : 'projectCode'">
        <el-input v-if="mode !== 'view'" :disabled="isProposal" style="width: 450px" v-model='form.projectCode'
          :maxlength="50" placeholder="请输入" />
        <span v-else>{{ form.projectCode }}</span>
      </el-form-item>

      <el-form-item :label="projectNature !== projectNatureEnum.projectNatureHorizontal ? '项目名称' : '合同名称'"
        prop="projectName">
        <el-input v-if="mode !== 'view'" style="width: 450px" v-model='form.projectName' :maxlength="50"
          placeholder="请输入" />
        <span v-else>{{ form.projectName }}</span>
      </el-form-item>

      <el-form-item label="项目分类" v-if="projectNature !== projectNatureEnum.projectNatureHorizontal" prop="projectType">
        <el-select v-if="mode !== 'view'" :disabled="isProposal" style="width: 450px" v-model="form.projectType"
          placeholder="请选择">
          <el-option
            v-for="dict of getDicListById(props.projectNature === projectNatureEnum.projectNatureHorizontal ? 6 : props.projectNature === projectNatureEnum.projectNatureSchool ? 27 : 5, props.dictList)"
            :key="dict.dataId" :label="dict.dataName" :value="dict.dataId" />
        </el-select>
        <span v-else>{{ form.projectTypeName }}</span>
      </el-form-item>

      <el-form-item label="负责人类型" prop="managerType">
        <el-radio-group v-if="mode !== 'view'" v-model="form.managerType" style="width: 450px">
          <el-radio v-for="item of managerTypeList" :key="item.value" :value="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
        <span v-else>{{ managerTypeList.find(i => i.value === form.managerType)?.label }}</span>
      </el-form-item>

      <el-form-item label="负责人姓名" prop="managerName">
        <el-input v-if="mode !== 'view'" style="width: 450px" :maxlength="50" v-model="form.managerName"
          placeholder="请输入" />
        <span v-else>{{ form.managerName }}</span>
      </el-form-item>

      <el-form-item label="负责人电话" prop="managerPhone">
        <el-input v-if="mode !== 'view'" style="width: 450px" :maxlength="11" v-model="form.managerPhone"
          placeholder="请输入" />
        <span v-else>{{ form.managerPhone }}</span>
      </el-form-item>

      <el-form-item label="工号">
        <el-input v-if="mode !== 'view'" style="width: 450px" :maxlength="50" v-model="form.employeeNumber"
          placeholder="请输入" />
        <span v-else>{{ form.employeeNumber }}</span>
      </el-form-item>

      <el-form-item label="项目级别" prop="projectLevel" v-if="projectNature !== projectNatureEnum.projectNatureHorizontal">
        <el-select v-if="mode !== 'view'" style="width: 450px" v-model="form.projectLevel" placeholder="请选择">
          <el-option v-for="dict of getDicListById(18, props.dictList)" :key="dict.dataId" :label="dict.dataName"
            :value="dict.dataId" />
        </el-select>
        <span v-else>{{ form.projectLevelName }}</span>
      </el-form-item>

      <el-form-item label="负责人邮箱" prop="managerEmail">
        <el-input v-if="mode !== 'view'" style="width: 450px" v-model='form.managerEmail' :maxlength="50"
          placeholder="请输入" />
        <span v-else>{{ form.managerEmail }}</span>
      </el-form-item>

      <el-form-item label="所属院系(部)" prop="department">
        <el-select v-if="mode !== 'view'" style="width: 450px" v-model="form.department" placeholder="请选择">
          <el-option v-for="dict of departmentList" :key="dict.value" :label="dict.title" :value="dict.value" />
        </el-select>
        <span v-else>{{ form.departmentName }}</span>
      </el-form-item>

      <el-form-item :label="projectNature !== projectNatureEnum.projectNatureHorizontal ? '项目类别' : '合同类别'"
        prop="projectCategory">
        <el-select v-if="mode !== 'view'" style="width: 450px" v-model="form.projectCategory" placeholder="请选择">
          <el-option
            v-for="dict of getDicListById(projectNature !== projectNatureEnum.projectNatureHorizontal ? 7 : 12, props.dictList)"
            :key="dict.dataId" :label="dict.dataName" :value="dict.dataId" />
        </el-select>
        <span v-else>{{ form.projectCategoryName }}</span>
      </el-form-item>

      <el-form-item label="统计年度" prop="statisticsYear">
        <el-select v-if="mode !== 'view'" :disabled="isProposal" style="width: 450px" v-model="form.statisticsYear"
          placeholder="请选择">
          <el-option v-for="dict of getDicListById(2, props.dictList)" :key="dict.dataId" :label="dict.dataName"
            :value="dict.dataId" />
        </el-select>
        <span v-else>{{ form.statisticsYearName }}</span>
      </el-form-item>

      <el-form-item :prop="projectNature !== projectNatureEnum.projectNatureHorizontal ? '' : 'sourceUnit'"
        :label="projectNature !== projectNatureEnum.projectNatureHorizontal ? '项目来源单位' : '委托单位'">
        <el-input v-if="mode !== 'view'" style="width: 450px" v-model='form.sourceUnit' :maxlength="50"
          placeholder="请输入" />
        <span v-else>{{ form.sourceUnit }}</span>
      </el-form-item>
      
      <el-form-item label="立项日期" :prop="isProposal ? '' : 'approvalTime'">
        <el-date-picker v-if="mode !== 'view'" :disabled="isProposal" style="width: 450px" v-model="form.approvalTime"
          type="date" placeholder="选择日期" />
        <span v-else>{{ form.approvalTime ? formateDate(form.approvalTime).format('YYYY-MM-DD') : '-' }}</span>
      </el-form-item>

      <el-form-item label="结项日期" :prop="isProposal ? '' : 'conclusionTime'">
        <el-date-picker v-if="mode !== 'view'" :disabled="isProposal" style="width: 450px" v-model="form.conclusionTime"
          type="date" placeholder="选择日期" />
        <span v-else>{{ form.approvalTime ? formateDate(form.conclusionTime).format('YYYY-MM-DD') : '-' }}</span>
      </el-form-item>

      <el-form-item label="项目经费(万元)" prop="projectFunding">
        <el-input-number :controls='false' :min="0" v-if="mode !== 'view'" style="width: 450px" :maxlength="10" :max="999999999"
          v-model="form.projectFunding" placeholder="请输入" />
        <span v-else>{{ form.projectFunding }}</span>
      </el-form-item>

      <el-form-item label="配套经费(万元)">
        <el-input-number :controls='false' :min="0" v-if="mode !== 'view'" style="width: 450px" :maxlength="10" :max="999999999"
          v-model="form.subsidiaryFunding" placeholder="请输入" />
        <span v-else>{{ form.subsidiaryFunding }}</span>
      </el-form-item>

      <el-form-item label="成果形式">
        <el-input v-if="mode !== 'view'" style="width: 450px" :maxlength="50" v-model="form.achievementForm"
          placeholder="请输入" />
        <span v-else>{{ form.achievementForm }}</span>
      </el-form-item>

      <el-form-item label="合作形式" :class="{'show-border': projectNature === projectNatureEnum.projectNatureHorizontal && mode === 'view'}">
        <el-select v-if="mode !== 'view'" style="width: 450px" v-model="form.cooperationForm" placeholder="请选择">
          <el-option v-for="dict of getDicListById(8, props.dictList)" :key="dict.dataId" :label="dict.dataName"
            :value="dict.dataId" />
        </el-select>
        <span v-else>{{ form.cooperationFormName }}</span>
      </el-form-item>

      <el-form-item label="一级学科" v-if="projectNature !== projectNatureEnum.projectNatureHorizontal">
        <el-select v-if="mode !== 'view'" style="width: 450px" v-model="form.firstDiscipline" placeholder="请选择">
          <el-option v-for="dict of getDicListById(3, props.dictList)" :key="dict.dataId" :label="dict.dataName"
            :value="dict.dataId" />
        </el-select>
        <span v-else>{{ form.firstDisciplineName }}</span>
      </el-form-item>

      <el-form-item label="国民经济行业" v-if="projectNature !== projectNatureEnum.projectNatureHorizontal">
        <el-select v-if="mode !== 'view'" style="width: 450px" v-model="form.economicSector" placeholder="请选择">
          <el-option v-for="dict of getDicListById(9, props.dictList)" :key="dict.dataId" :label="dict.dataName"
            :value="dict.dataId" />
        </el-select>
        <span v-else>{{ form.economicSectorName }}</span>
      </el-form-item>

      <el-form-item label="研究类别" v-if="projectNature !== projectNatureEnum.projectNatureHorizontal">
        <el-select v-if="mode !== 'view'" style="width: 450px" v-model="form.researchCategory" placeholder="请选择">
          <el-option v-for="dict of getDicListById(4, props.dictList)" :key="dict.dataId" :label="dict.dataName"
            :value="dict.dataId" />
        </el-select>
        <span v-else>{{ form.researchCategoryName }}</span>
      </el-form-item>

      <el-form-item label="学科分类"
        :prop="projectNature !== projectNatureEnum.projectNatureHorizontal ? 'classification' : ''">
        <el-select v-if="mode !== 'view'" style="width: 450px" v-model="form.classification" placeholder="请选择">
          <el-option v-for="dict of getDicListById(10, props.dictList)" :key="dict.dataId" :label="dict.dataName"
            :value="dict.dataId" />
        </el-select>
        <span v-else>{{ form.classificationName }}</span>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ProjectBaseCreateDTO } from '@/types/project/request';
import { managerTypeList } from '../../constText';
import { createProjectApi, getBaseDetailsApi, updateProjectApi } from '@/api/project';
import { BaseSuccessRespDTO, DictionaryListRespVO } from '@/api/project/types';
import { getDicListById } from '../../utils';
import { DepartmentPageVO } from '@/api/system/user/type';
import { projectNatureEnum } from '@/utils/constEnum';
import formateDate from '@/utils/formateDate';

// 字典code 1：所属院系（部） 2：统计年度 3：一级学科 4：研究类别 5：项目分类(纵向) 6：项目分类（横向）7：项目类别 8：合作形式 9：国民经济行业 10学科分类11：合同类别（纵向） 12：合同类别（横向）13：职称 14：专业
const props = defineProps({
  dictList: {
    type: Array as PropType<DictionaryListRespVO[]>,
    default: () => []
  },
  projectNature: { // 项目性质，1纵向项目 2校级项目 3横向项目
    type: Number,
    default: 1
  },
  mode: {
    type: String as PropType<'add' | 'edit' | 'view'>,
    default: 'add'
  },
  projectId: {
    type: String,
    default: ''
  },
  departmentList: {
    type: Array as PropType<DepartmentPageVO[]>,
    default: () => []
  },
  isProposal: { // 是否为立项状态
    type: Boolean,
    default: false
  }
})

const route = useRoute()

const ruleFormRef = ref()

const router = useRouter()

import useUserStore from '@/store/modules/user'

const userStore = useUserStore()

const { proxy } = getCurrentInstance();

const form = ref<ProjectBaseCreateDTO>({
  id: route.query.projectId as string,
  employeeNumber: '',
  /**
     * 成果形式
     */
  achievementForm: '',
  /**
   * 立项日期
   */
  approvalTime: '',
  /**
   * 学科分类
   */
  classification: undefined,
  /**
   * 结项日期
   */
  conclusionTime: '',
  /**
   * 合作形式
   */
  cooperationForm: undefined,
  /**
   * 所属院系(部)
   */
  department: undefined,
  /**
   * 国民经济行业
   */
  economicSector: undefined,
  /**
   * 一级学科
   */
  firstDiscipline: undefined,
  /**
   * 是否暂存
   */
  isTemp: false,
  /**
   * 负责人邮箱
   */
  managerEmail: '',
  /**
   * 负责人
   */
  managerName: '',
  /**
   * 负责人电话
   */
  managerPhone: '',
  /**
   * 负责人类型;1本校教师 2本校学生 3校外人员
   */
  managerType: undefined,
  /**
   * 通知id
   */
  noticeId: undefined,
  /**
   * 项目类别
   */
  projectCategory: undefined,
  /**
   * 项目编码
   */
  projectCode: '',
  /**
   * 项目经费（万元）
   */
  projectFunding: undefined,
  /**
   * 项目级别
   */
  projectLevel: undefined,
  /**
   * 项目(合同)名称
   */
  projectName: '',
  /**
   * 项目性质;1纵向项目 2校级项目 3横向项目
   */
  projectNature: props.projectNature,
  /**
   * 项目分类
   */
  projectType: undefined,
  /**
   * 研究类别
   */
  researchCategory: undefined,
  /**
   * 项目来源单位
   */
  sourceUnit: '',
  /**
   * 统计年度
   */
  statisticsYear: undefined,
  /**
   * 配套经费（万元）
   */
  subsidiaryFunding: undefined,
})

// 获取详情
const { run: getBaseDetails } = useRequest(getBaseDetailsApi, {
  manual: true,
  onSuccess: (res) => {
    res.statusTemp = res.status
    // tips: 这里把status 删掉，要不然横向项目查看会报错
    res.status = undefined
    form.value = res
    setTimeout(() => {
      ruleFormRef.value.clearValidate()
    }, 0)
  }
})

watch(
  () => [props.mode, props.projectId],
  () => {
    if (props.mode !== 'add' || props.projectId || route.query.projectId) {
      getBaseDetails({ id: props.projectId || route.query.projectId })
    }

    // 创建项目时，需要回显一些信息
    if (props.mode === 'add' && !props.projectId && !route.query.projectId) {
      const { phone, departmentId: department, name: managerName, email, code } = userStore.$state
      form.value.managerPhone = phone // 电话
      form.value.department = department // 部门
      form.value.managerEmail = email // 邮箱
      form.value.employeeNumber = code // 编码
      form.value.managerName = managerName // 姓名
    }

    if (props.isProposal && route.query.noticesId) {
      if (route.query.projectType) {
        form.value.projectType = route.query.projectType as string
      }

      if (route.query.statisticsYear) {
        form.value.statisticsYear = route.query.statisticsYear as string
      }
    }
  },
  {
    immediate: true
  }
)


// 项目性质名称
const projectNatureName = computed(() => {
  return props.projectNature === projectNatureEnum.projectNaturePortrait ? '纵向项目' : props.projectNature === projectNatureEnum.projectNatureSchool ? '校级项目' : '横向项目'
})

// 校验email
const validEmail = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入邮箱'))
  } else {
    if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)) {
      callback(new Error('邮箱格式不正确'))
    } else {
      callback()
    }
  }
}

// 校验手机号码
const validPhone = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入电话'))
  } else {
    if (!/^1\d{10}$/.test(value)) {
      callback(new Error('手机号格式不正确'))
    } else {
      callback()
    }
  }
}

// 校验项目经费, 只能是合规的数字or带小数点数字
const validProjectFunding = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入经费金额'))
  } else {
    if (String(value).match(/^\d+(\.\d{1,10})?$/)) {
      callback()
    } else {
      callback(new Error('请输入正确的经费金额'))
    }
  }
}

const rules = ref({
  employeeNumber: [
    { required: true, message: '请填写', trigger: 'blur' },
  ],
  projectName: [
    { required: true, message: '请填写', trigger: 'blur' },
  ],
  classification: [
    { required: true, message: '请选择', trigger: 'change' },
  ],
  projectCode: [
    { required: true, message: '请选择', trigger: 'blur' },
  ],
  approvalTime: [
    { required: true, message: '请填写', trigger: 'blur' },
  ],
  conclusionTime: [
    { required: true, message: '请填写', trigger: 'blur' },
  ],
  sourceUnit: [
    { required: true, message: '请选择', trigger: 'blur' },
  ],
  projectType: [
    { required: true, message: '请选择', trigger: 'change' },
  ],
  managerType: [
    { required: true, message: '请选择负责人类型', trigger: 'change' },
  ],
  managerName: [
    { required: true, message: '请填写负责人姓名', trigger: 'blur' },
  ],
  managerPhone: [
    { required: true, trigger: 'blur', validator: validPhone },
  ],
  managerEmail: [
    { required: true, trigger: 'blur', validator: validEmail },
  ],
  department: [
    { required: true, message: '请选择所属院系(部)', trigger: 'change' },
  ],
  projectCategory: [
    { required: true, message: '请选择项目类别', trigger: 'change' },
  ],
  statisticsYear: [
    { required: true, message: '请选择统计年度', trigger: 'change' },
  ],
  projectLevel: [
    { required: true, message: '请选择项目级别', trigger: 'change' },
  ],
  projectFunding: [
    { required: true, trigger: 'blur', validator: validProjectFunding },
  ],
  subsidiaryFunding: [
    { required: true, trigger: 'blur', validator: validProjectFunding },
  ],
})

// 暂存or创建项目
const { runAsync: createPrd } = useRequest(createProjectApi, {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO, params) => {
    form.value.id = res?.id

    if (res.isSuccess) {
      ElMessage.success('操作成功！')
    }
    if (params[0].isTemp) {

      proxy.$tab.closePage()
      const { path, query } = router.currentRoute.value

      setTimeout(() => {
        router.push({
          path,
          query: {
            ...query,
            projectId: res.id,
          }
        })
      }, 300)
    }

    return res
  }
})

// 暂存
const { runAsync: updatePrd } = useRequest(updateProjectApi, {
  manual: true,
  onSuccess: (res: BaseSuccessRespDTO,) => {
    if (form.value.id && res.isSuccess) {
      ElMessage.success('操作成功！')
    }

    return res
  }
})

const onCreateProject = async (isTemp) => {
  if (!form.value.id) {
    return await createPrd({ ...form.value, isTemp, noticeId: route.query.noticesId })
  } else {
    return await updatePrd({ ...form.value, isTemp, noticeId: route.query.noticesId })
  }
}

// 创建项目
const createProject = async (isTemp: boolean = false, item: Record<string, any> = {}) => {
  if (item.id) {
    form.value.id = item.id
  }

  // 通过 formateDate 判断立项时间不能大于结项时间， 通过dayjs判断是否在立项时间之前, 可以相等
  if (form.value.approvalTime && form.value.conclusionTime) {
    if (formateDate(form.value.approvalTime).isAfter(formateDate(form.value.conclusionTime))) {
      ElMessage.error('立项时间不能大于结项时间')
      return false
    }
  }

  // 暂存
  if (isTemp) {
    ruleFormRef.value.clearValidate()
    await onCreateProject(isTemp)
    return
  }
  return new Promise((resolve) => {
    ruleFormRef.value.validate(async (valid) => {
      if (valid) {
        await onCreateProject(isTemp)
        return resolve(form.value)
      } else {
        resolve(false)
      }
    })
  })
}

defineExpose({
  createProject,
  formVal: computed(() => form.value),
})

</script>
<style scoped lang='scss'>
.form {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

.form-views {
  border: 1px solid #BEDAFF;
  border-top: none;
  border-left: none;
  
  :deep(.el-form-item__label) {
    border: 1px solid #BEDAFF;
    border-bottom: 0;
    border-right: 0;
    line-height: 50px;
    height: 50px;
    background-color: #f6faff;
    padding-left: 16px;
  }
  
  :deep(.el-form-item__content) {
    border: 1px solid #BEDAFF;
    border-bottom: 0;
    border-right: 0;
    padding-left: 16px;
    line-height: 50px;
    height: 50px;
  }
  
  :deep(.el-form-item--default) {
    margin-bottom: 0;
  }

  .show-border {
    :deep(.el-form-item__label) {
      border-bottom: 1px solid #BEDAFF;
    }
    :deep(.el-form-item__content) {
      border-bottom: 1px solid #BEDAFF;
    }
  }
}
</style>